# -*- coding: UTF-8 -*-


from .baseview import BaseView
from .editmodel import EditModel


import copy


class FormView(BaseView):
    def __init__(self, action_id, **kwargs):
        super().__init__(action_id, type='form', **kwargs)
        self.edit_model = None
        #

    @property
    def view_info(self):

        view = copy.deepcopy(self.action_info['views']['form'])
        view['fields'] = self.fields

        return {
            'action': self.action_info,
            'view': view
        }

    def _read_one(self, res_id):
        Model = self.Model
        fields = self.fields_list
        if 'display_name' not in fields:
            fields.append('display_name')

        res = Model.read(res_id, fields=fields)
        return res[0]

    def read(self, res_id):
        return self._read_one(res_id)

    def _edit_model_get(self, record=None, values=None):
        return EditModel(viewmodel=self, record=record, values=values)

    def set_editable(self, record=None):
        self.edit_model = self._edit_model_get()
        return self.edit_model.set_editable(record)

    def onchange_new(self):
        self.edit_model = self._edit_model_get()
        return self.edit_model.onchange_new()

    def onchange(self, fname, value):
        return self.edit_model.onchange(fname, value)

    def commit(self, **kwargs):
        return self.edit_model.commit(**kwargs)

    def _get_values_for_write(self, record, values):
        values2 = self.Model._get_values_for_write(record, values)
        return values2
